package com.canary;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 自定义规则
 *
 * @author dzh
 * @date 2023/1/4 8:26
 */
@Component
@ConditionalOnProperty(name = "canary.rule", havingValue = "custom")
public class CustomRule implements IRule {
    ILoadBalancer loadBalancer;

    @Override
    public Server choose(Object key) {
        List<Server> servers = loadBalancer.getReachableServers();
        if (servers.size() < 1) {
            return null;
        }
        return servers.get(0);
    }

    @Override
    public void setLoadBalancer(ILoadBalancer lb) {
        // 过滤出来灰度服务和默认服务
        loadBalancer = lb;
    }

    @Override
    public ILoadBalancer getLoadBalancer() {
        return loadBalancer;
    }
}
